package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Voice;
import com.itheima.domain.vo.VoiceVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.PeachBlossomService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class PeachBlossomManager {

    @Reference
    private PeachBlossomService peachBlossomService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FastFileStorageClient client;  //存储的客户端  注入会报错 , 不影响执行
    @Autowired
    private FdfsWebServer fdfsWebServer; // tracker的服务器  注入会报错 , 不影响执行


    /**
     * 1.保存语音
     */
    public void saveVoice(MultipartFile soundFile) throws IOException {

//        fastdfs存储音频
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                FileUtil.extName(soundFile.getOriginalFilename()), null);
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        Voice voice = new Voice();
        voice.setUserId(UserHolder.getId());
        voice.setSoundUrl(soundUrl);
        voice.setRemainingTimes(4);
        peachBlossomService.saveVoice(voice);
    }

    /**
     * 2.查询语音
     */


    public VoiceVo findVoice() {

//      1.查询所有表中用户，拿到Pid
        List<Voice> allVoice = peachBlossomService.findAllVoice();
        List<Long> pidList = new ArrayList();

        if (CollectionUtil.isNotEmpty(allVoice)) {
            for (Voice voice : allVoice) {
                Long pid = voice.getPid();
                pidList.add(pid);
            }
        }

        Long randomPid = pidList.get((int) (Math.random() * pidList.size()));

//      2.判断当前用户可接收语音次数
//        查询当前用户id
        Long myId = UserHolder.getId();
//        从redis中获取setRemainingTimes
        String remainingTime = stringRedisTemplate.opsForValue().get(ConstantUtil.VOICE_REMAININGTIMES + myId);
        Integer remainingTimes = Integer.valueOf(remainingTime);
        if (remainingTimes == 0) {
            return null;
        }
//        setRemainingTimes减一 存回redis
        Integer number = remainingTimes - 1;
        stringRedisTemplate.opsForValue().set(ConstantUtil.VOICE_REMAININGTIMES + myId, number.toString());

//        3.判断语音用户是否是自己，是,重新获取pid,不是,执行查询返回数据
        Voice voice = peachBlossomService.findVoiceByPid((long) randomPid);
        Long voiceUserId = voice.getUserId();
        if (myId.equals(voiceUserId)) {
            return findVoice();
        } else {

//        4.移除被接收过的语音
            peachBlossomService.deleteVoiceByPid((long) randomPid);

//        5.获取语音用户信息
            UserInfo userInfo = userInfoService.findById(voiceUserId);

//        6.封装数据
            VoiceVo voiceVo = new VoiceVo();
            voiceVo.setUserInfo(userInfo);
            voiceVo.setVoice(voice);
            voiceVo.setUserId(voice.getUserId().toString());
            voiceVo.setRemainingTimes(number);
            return voiceVo;
        }
    }
}


